﻿using JzSport.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Api
{
    /// <summary>
    /// 查找用户
    /// </summary>
    class SearchUserAction : AuthGetAction<Params.SearchUserParams,
        Results.SearchUserResult>
    {
        protected override ActionResult<Results.SearchUserResult> OnExecute(ActionContext context, 
            SysParameters sysParameters,
            Params.SearchUserParams opParams)
        {
            int limit = 50;
            int start = opParams.Page * limit;
            ServiceResult<PagedList<Model.Data.SearchUser4UserData>> serviceResult = new AccountService().Search4User(context.AccountId, opParams.Filter, start, limit);

            Results.SearchUserResult actionResult = new Results.SearchUserResult();

            if (serviceResult.ErrorCode == ErrorCode.NoError)
            {
                actionResult.Start = start;
                actionResult.Limit = limit;
                actionResult.Total = serviceResult.Data.Total;
                actionResult.Page = opParams.Page;
                for (int index = 0; index < serviceResult.Data.Items.Count; index++)
                {
                    Results.SearchUserResult.UserItem item = new Results.SearchUserResult.UserItem();
                    item.Id = serviceResult.Data.Items[index].Account.Id;
                    item.Name = serviceResult.Data.Items[index].Account.Name;
                    item.NickName = serviceResult.Data.Items[index].Account.NickName;
                    item.AvatarUrl = string.Format("{0}{1}", Configs.BaseWebUrl, serviceResult.Data.Items[index].Account.AvatarUrl);
                    item.IsFriend = serviceResult.Data.Items[index].IsFriend;
                    actionResult.Items.Add(item);
                }

                if (actionResult.Start + actionResult.Items.Count >= actionResult.Total)
                {
                    actionResult.IsTheEnd = true;
                }
                else
                {
                    actionResult.IsTheEnd = false;
                }

                return new ActionResult<Results.SearchUserResult>("1.0.1", true, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
            }
            return new ActionResult<Results.SearchUserResult>("1.0.1", false, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
        }
    }
}
